<?php namespace App\Services;

use App\Models\Catalog;
use Illuminate\Http\Request;
use Exception;

class CatalogService
{

    public function getList(Request $request)
    {
        $search = Catalog::where([]);
        if ($level = $request->input('level'))
            $search->where('level', $level);
        if ($name = $request->input('name'))
            $search->where('name', 'like', '%' . $name . '%');
        return $search->orderBy($request->input('orderField', 'id'), $request->input('orderDirection', 'asc'))
            ->paginate($request->input('pageSize', config('view')['numPerPage']));
    }

    public function create(Array $data)
    {
        $level = 1;
        if ($p_catalog = Catalog::find($data['p_id'])) {
            $level = $p_catalog->level + 1;
        }
        return Catalog::create([
            'name' => $data['name'],
            'p_id' => $data['p_id'],
            'level' => $level
        ]);
    }

    public function update($id, Array $data)
    {
        if($id == $data['p_id']){
            throw new Exception('不能绑定到自身');
        }
        $catalog = Catalog::find($id);
        $p_catalog = Catalog::find($data['p_id']);
        $catalog->name = $data['name'];
        $catalog->p_id = $data['p_id'];
        $catalog->level = $p_catalog ? $p_catalog->level + 1 : 1;
        return $catalog->save();
    }

    public function delete($id)
    {
        if (Catalog::where('p_id', $id)->count() > 0) {
            throw new Exception('存在下级分类，不能删除');
        }
        return Catalog::find($id)->delete();
    }
}